<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px" class="search-form">
          <el-form-item label="所属级别" prop="gradeLevel">
            <el-select v-model="queryParams.gradeLevel" placeholder="请选择所属级别" clearable>
              <el-option v-for="dict in school_grade_level" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="所属学部" prop="facultyId">
            <el-select v-model="queryParams.facultyId" placeholder="请选择所属学部" clearable>
              <el-option v-for="dict in faculty_type" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="班级名称" prop="className">
            <el-input v-model="queryParams.className" placeholder="请输入班级名称" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="负责人" prop="gradePrincipal">
            <el-input v-model="queryParams.gradePrincipal" placeholder="请输入负责人" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAddGrade" v-hasPermi="['grade:gradeInfo:add']">新增年级</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['class:classInfo:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['class:classInfo:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button icon="Download" @click="handleExport" v-hasPermi="['class:classInfo:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table
        height="calc(100vh - 370px)"
        v-loading="loading"
        :data="gradeClassList"
        @selection-change="handleSelectionChange"
        @row-dblclick="(row: any, column: any, event: Event) => handleUpdate(row)"
        :row-key="(row) => row.id + row.type"
        default-expand-all
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="" align="center" prop="id" v-if="false" />
        <el-table-column label="组数" align="left" prop="name" />
        <el-table-column label="级别" align="center" prop="gradeLevel">
          <template #default="scope">
            <dict-tag :options="school_grade_level" :value="scope.row.gradeLevel" />
          </template>
        </el-table-column>
        <el-table-column label="学部" align="center" prop="facultyId">
          <template #default="scope">
            <dict-tag :options="faculty_type" :value="parseInt(scope.row.facultyId)" />
          </template>
        </el-table-column>
        <el-table-column label="负责人" align="center" prop="principals" />
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['class:classInfo:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['class:classInfo:remove']"></el-button>
            </el-tooltip>
            <el-tooltip content="增加班级" placement="top" v-if="'grade' === scope.row.type">
              <el-button link type="primary" plain icon="Plus" @click="handleAdd(scope.row)" v-hasPermi="['class:classInfo:add']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改班级信息对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="800px" append-to-body>
      <el-form ref="classInfoFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="所属年级" required>
          <el-autocomplete
            v-model="form.gradeName"
            :fetch-suggestions="searchGradeInfo"
            :trigger-on-focus="false"
            placeholder="请输入年级"
            @select="((item) => handleSelectGrade(item))"
            disabled
          >
            <template #default="{ item }">
              <div class="value">{{ item.gradeName }}:{{ item.gradeLevel }}</div>
            </template>
          </el-autocomplete>
        </el-form-item>
        <el-row gutter="10">
          <el-col span="10">
            <el-form-item label="班级" prop="classSeq">
              <el-input v-model="form.classSeq" style="max-width: 250px" placeholder="序号" @change="genClassName">
                <template #prepend>{{form.gradeName}}</template>
                <template #append>班</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col span="12">
            <el-form-item label="班级名称" prop="className">
              <el-input v-model="form.className" :disabled="disabledClassName" style="max-width: 192px; padding-right: 5px" />
              <el-button size="small" type="primary" v-if="disabledClassName" @click="() => disabledClassName = !disabledClassName">自定义</el-button>
              <el-button
                size="small"
                type="primary"
                v-if="!disabledClassName"
                @click="() => { genClassName(); disabledClassName = !disabledClassName; }"
                >还原标准名称</el-button
              >
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-for="(principal, index) in form.principals">
          <el-col span="5">
            <el-form-item
              label="负责人"
              :prop="'principals.' + index + '.staffId'"
              :rules="{ required: true, message: '负责人不能为空', trigger: 'blur' }"
            >
              <el-select v-model="principal.staffId" placeholder="请选择">
                <el-option v-for="dict in staffOptions" :key="dict.staffId" :label="dict.realName" :value="dict.staffId"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col span="5">
            <el-form-item
              label="角色"
              :prop="'principals.' + index + '.roleId'"
              :rules="{ required: true, message: '负责人角色不能为空', trigger: 'blur' }"
            >
              <el-select v-model="principal.roleId" placeholder="请选择" style="width: 120px">
                <el-option v-for="dict in school_class_role" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col span="5">
            <el-form-item
              label="科目"
              :prop="'principals.' + index + '.subjectId'"
              :rules="{ required: true, message: '负责人科目不能为空', trigger: 'blur' }"
            >
              <el-select v-model="principal.subjectId" placeholder="请选择" style="width: 120px">
                <el-option v-for="dict in school_subject" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col span="1" style="padding-left: 10px">
            <el-button type="danger" plain icon="Delete" @click="removeClassPrincipal(principal)"></el-button>
          </el-col>
        </el-row>
        <el-form-item>
          <el-button plain icon="Plus" @click="addClassPrincipal">新增负责人</el-button>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" rows="3" v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 添加或修改年级信息对话框 -->
    <el-dialog :title="gradeDialog.title" v-model="gradeDialog.visible" width="750px" append-to-body>
      <el-form ref="gradeInfoFormRef" :model="gradeForm" :rules="rules" label-width="80px">
        <el-row gutter="10">
          <el-col span="12">
            <el-form-item label="级别" prop="gradeLevel">
              <el-select v-model="gradeForm.gradeLevel" placeholder="请选择级别">
                <el-option v-for="dict in school_grade_level" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col span="12">
            <el-form-item label="学部" prop="facultyId" required>
              <el-select v-model="gradeForm.facultyId" placeholder="请选择学部">
                <el-option v-for="dict in faculty_type" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="年级名称" prop="gradeName">
          <el-input v-model="gradeForm.gradeName" placeholder="请输入年级名称" style="width: 83%" />
        </el-form-item>
        <el-row gutter="10" v-for="(principal, index) in gradeForm.principals">
          <el-col span="11">
            <el-form-item
              label="负责人"
              :prop="'principals.' + index + '.staffId'"
              :rules="{ required: true, message: '负责人不能为空', trigger: 'blur' }"
            >
              <el-select v-model="principal.staffId" placeholder="请选择">
                <el-option v-for="dict in staffOptions" :key="dict.staffId" :label="dict.realName" :value="dict.staffId"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col span="11">
            <el-form-item
              label="职务"
              :prop="'principals.' + index + '.postId'"
              :rules="{ required: true, message: '负责人职务不能为空', trigger: 'blur' }"
            >
              <el-select v-model="principal.postId" placeholder="请选择">
                <el-option v-for="dict in school_post" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col span="2">
            <el-button type="danger" plain icon="Delete" @click="removeGradePrincipal(principal)"></el-button>
          </el-col>
        </el-row>
        <el-form-item>
          <el-button plain icon="Plus" @click="addGradePrincipal">新增负责人</el-button>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" rows="3" v-model="gradeForm.remark" style="width: 83%" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitGradeForm">确 定</el-button>
          <el-button @click="cancelGradeForm">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ClassInfo" lang="ts">
import { pageClassInfo, getClassInfo, delClassInfo, addClassInfo, updateClassInfo } from '@/api/office/class';
import { ClassInfoVO, ClassInfoQuery, ClassInfoForm } from '@/api/office/class/types';
import { GradeInfoForm } from '@/api/office/grade/types';
import { addGradeInfo, updateGradeInfo, listGradeInfo, pageGradeInfo, getGradeInfo, delGradeInfo } from '@/api/office/grade';
import { uuid } from '@/utils/ruoyi';
import { listStaff } from '@/api/office/staff';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { school_grade_level, faculty_type, school_post, school_subject, school_class_role } = toRefs<any>(
  proxy?.useDict('school_grade_level', 'faculty_type', 'school_post', 'school_subject', 'school_class_role')
);

const gradeClassList = ref<any[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const classIds = ref<Array<string | number>>([]);
const gradeIds = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const disabledClassName = ref(true);
const staffOptions = ref<any[]>([]);
const queryFormRef = ref<ElFormInstance>();
const classInfoFormRef = ref<ElFormInstance>();
const gradeInfoFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const gradeDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: ClassInfoForm = {
  gradeId: undefined,
  className: undefined,
  classSeq: undefined,
  principals: [],
  remark: undefined
};

const data = reactive<PageData<ClassInfoForm, ClassInfoQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    gradeLevel: undefined,
    className: undefined,
    facultyId: undefined,
    gradePrincipal: undefined,
    params: {}
  },
  rules: {
    gradeLevel: [{ required: true, message: '级别不能为空', trigger: 'blur' }],
    facultyId: [{ required: true, message: '学部不能为空', trigger: 'blur' }],
    gradeName: [{ required: true, message: '年级名称不能为空', trigger: 'blur' }],
    gradeId: [{ required: true, message: '年级id不能为空', trigger: 'blur' }],
    className: [{ required: true, message: '班级名称不能为空', trigger: 'blur' }],
    classSeq: [{ required: true, message: '班级序号不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

const initGradeFormData: GradeInfoForm = {
  id: undefined,
  gradeName: undefined,
  gradeCode: undefined,
  gradeLevel: undefined,
  facultyId: undefined,
  principals: [],
  remark: undefined
};

const gradeForm = ref({ ...initGradeFormData });

const addClassPrincipal = () => {
  form.value.principals.push({ idx: uuid(), staffId: undefined, postId: undefined });
};

const removeClassPrincipal = (item: any) => {
  form.value.principals = form.value.principals.filter((e) => e.idx !== item.idx);
};

const addGradePrincipal = () => {
  gradeForm.value.principals.push({ idx: uuid(), staffId: undefined, postId: undefined });
};

const removeGradePrincipal = (item: any) => {
  gradeForm.value.principals = gradeForm.value.principals.filter((e) => e.idx !== item.idx);
};

/** 查询班级信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await pageGradeInfo(queryParams.value);
  gradeClassList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

const cancelGradeForm = () => {
  resetGradeForm();
  gradeDialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  form.value.principals = [];
  classInfoFormRef.value?.resetFields();
};

const resetGradeForm = () => {
  gradeForm.value = { ...initGradeFormData };
  gradeForm.value.principals = [];
  gradeInfoFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: any[]) => {
  gradeIds.value = selection.filter((item) => item.type === 'grade').map((item) => item.id);
  classIds.value = selection.filter((item) => item.type === 'class').map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = (row: any) => {
  reset();
  loadStaffOptions();
  dialog.visible = true;
  dialog.title = '添加班级信息';
  form.value.gradeName = row.name;
  form.value.gradeId = row.id;
};

const handleAddGrade = () => {
  resetGradeForm();
  loadStaffOptions();
  gradeDialog.visible = true;
  gradeDialog.title = '添加年级信息';
};

const genClassName = () => {
  if (form.value.classSeq) {
    form.value.className = form.value.gradeName + '(' + form.value.classSeq + ')班';
  }
};

/** 修改按钮操作 */
const handleUpdate = async (row?: any) => {
  reset();
  await loadStaffOptions();
  const _id = row?.id || gradeIds.value[0] || classIds.value[0];
  let type = row ? row.type : (gradeIds.value[0] ? 'grade' : 'class' );
  if (type === 'grade') {
    const res = await getGradeInfo(_id);
    Object.assign(gradeForm.value, res.data);
    gradeForm.value.principals.forEach(e => e.idx = uuid());
    gradeDialog.visible = true;
    gradeDialog.title = '修改年级信息';
  } else {
    const res = await getClassInfo(_id);
    Object.assign(form.value, res.data);
    form.value.principals.forEach(e => e.idx = uuid());
    dialog.visible = true;
    dialog.title = '修改班级信息';
  }
};

/** 提交按钮 */
const submitForm = () => {
  classInfoFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateClassInfo(form.value).finally(() => (buttonLoading.value = false));
        proxy?.$modal.msgSuccess('修改成功');
      } else {
        await addClassInfo(form.value).finally(() => (buttonLoading.value = false));
        proxy?.$modal.msgSuccess('新增成功');
      }
      dialog.visible = false;
      await getList();
    }
  });
};

const loadStaffOptions = async () => {
  const res = await listStaff();
  staffOptions.value = res.rows;
}

const searchGradeInfo = (queryString, cb) => {
  listGradeInfo({ gradeName: queryString }).then((response) => {
    cb(response.rows);
  });
};

const handleSelectGrade = (item: any) => {
  form.value.gradeName = item.gradeName + ':' + item.gradeLevel;
  form.value.gradeId = item.id;
};

/**
 * 新增年级
 */
const submitGradeForm = () => {
  gradeInfoFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (gradeForm.value.id) {
        await updateGradeInfo(gradeForm.value).finally(() => (buttonLoading.value = false));
        proxy?.$modal.msgSuccess('修改成功');
      } else {
        await addGradeInfo(gradeForm.value).finally(() => (buttonLoading.value = false));
        proxy?.$modal.msgSuccess('新增成功');
      }
      gradeDialog.visible = false;
      await getList();
    }
  });
};

const deleteGrade = async (row?: any) => {
  const _ids = row ? [row.id] : ids.value;
  let msg = gradeClassList.value
    .filter((e) => _ids.find((id) => e.id === id))
    .map((e) => e.name)
    .join(',');
  await proxy?.$modal.confirm('是否确认删除年级名称为"' + msg + '"的数据项？').finally(() => (loading.value = false));
  await delGradeInfo(_ids);
};

/** 删除按钮操作 */
const handleDelete = async (row?: any) => {
  let type = row ? row.type : 'grade';
  if (type === 'grade') {
    await deleteGrade(row);
  } else {
    const _ids = row?.id || ids.value;
    await proxy?.$modal.confirm('是否确认删除班级名称为"' + row.name + '"的数据项？').finally(() => (loading.value = false));
    await delClassInfo(_ids);
  }
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'office/grade/export',
    {
      ...queryParams.value
    },
    `班级信息_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  getList();
});
</script>
